package com.liyunc.demo.comp.captcha.impl;

import com.liyunc.demo.comp.captcha.CaptchaConfig;
import com.liyunc.demo.comp.captcha.CaptchaPayload;
import com.liyunc.demo.comp.captcha.CaptchaService;
import lombok.extern.log4j.Log4j2;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * @author liyuncong
 * @version 1.0
 * @file CaptchaServiceImpl
 * @brief CaptchaServiceImpl
 * @details CaptchaServiceImpl
 * @date 2022-06-08
 *
 * Edit History
 * ----------------------------------------------------------------------------
 * DATE                        NAME               DESCRIPTION
 * 2022-06-08                      liyuncong          Created
 */
@Log4j2
public class CaptchaServiceImpl implements CaptchaService {

    @Override
    public CaptchaPayload generate(CaptchaConfig config) {
        StringBuilder sb = new StringBuilder();
        //1.创建空白图片
        BufferedImage image = new BufferedImage(
            config.getImageWidth(),
            config.getImageHeight(),
            BufferedImage.TYPE_INT_RGB);
        //2.获取图片画笔
        Graphics graphics = image.getGraphics();
        //3.设置画笔颜色
        graphics.setColor(Color.LIGHT_GRAY);
        //4.绘制矩形背景
        graphics.fillRect(0, 0, config.getImageWidth(), config.getImageHeight());
        //5.画随机数字
        Random random = new Random();
        for (int i = 0; i < config.getImageCharNumber(); i++) {
            //取随机字符索引
            int index = random.nextInt(config.getRandString().length);
            //设置随机颜色
            graphics.setColor(getRandomColor());
            //设置字体大小
            graphics.setFont(new Font(null, Font.BOLD + Font.ITALIC, config.getImageFontSize()));
            //画字符
            graphics.drawString(config.getRandString()[index] + "",
                i * config.getImageWidth() / config.getImageCharNumber(),
                config.getImageHeight() * 2 / 3);
            //记录字符
            sb.append(config.getRandString()[index]);
        }
        //6.画干扰线
        for (int j = 0; j < config.getImageLineSize(); j++) {
            //设置随机颜色
            graphics.setColor(getRandomColor());
            //画随机线
            graphics.drawLine(
                random.nextInt(config.getImageWidth()),
                random.nextInt(config.getImageHeight()),
                random.nextInt(config.getImageWidth()),
                random.nextInt(config.getImageHeight()));
        }
        return new CaptchaPayload(image, sb.toString(), config.getExpireTime());
    }

    /**
     * 获取随机颜色.
     */
    private static Color getRandomColor() {
        final int number = 256;
        Random random = new Random();
        return new Color(random.nextInt(number), random.nextInt(number), random.nextInt(number));
    }
}
